package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.config.DefaultUserConfig;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

@Service
public class TodayBestService {

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @Autowired
    private UserService userService;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

//    @Value("${tanhua.sso.default.user}")
//    private Long defaultUserId;

    @Autowired
    private DefaultUserConfig defaultUserConfig;

    public TodayBest queryTodayBest(String token) {
        Long userId = this.userService.checkToken(token);
        if(userId == null) {
            return null;
        }

        //通过dubbo服务查询得分最高的用户
        RecommendUser recommendUser = this.recommendUserApi.queryWithMaxScore(userId);
        if(ObjectUtil.isEmpty(recommendUser)) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(defaultUserConfig.getUserId());
            recommendUser.setToUserId(userId);
            recommendUser.setScore(RandomUtil.randomDouble(80, 99));
        }

        UserInfo userInfo = this.userInfoApi.queryByUserId(recommendUser.getUserId());
        TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setId(userInfo.getId());
        todayBest.setFateValue(recommendUser.getScore().longValue());

        return todayBest;
    }

    public PageResult queryRecommendation(RecommendUserQueryParam queryParam) {
        Long userId = UserThreadLocal.get();
        if(userId == null) {
            return null;
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());

        PageInfo<RecommendUser> recommendUserPageInfo = this.recommendUserApi.queryPageInfo(userId, queryParam.getPage(), queryParam.getPagesize());
        List<RecommendUser> records = recommendUserPageInfo.getRecords();
        if(CollUtil.isEmpty(records)) {
            //TODO 默认的推荐列表
            return pageResult;
        }

        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = this.userInfoApi.queryByUserIdList(userIdList);
        if(CollUtil.isEmpty(userInfos)) {
            return pageResult;
        }

        ArrayList<TodayBest> todayBests = new ArrayList<>();

        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setId(userInfo.getId());
            for (RecommendUser recommendUser : records) {
                if(ObjectUtil.equal(recommendUser.getUserId(), userInfo.getUserId())) {
                    todayBest.setFateValue(recommendUser.getScore().longValue());
                }
            }
            todayBests.add(todayBest);
        }

        Collections.sort(todayBests, (o1, o2) -> Convert.toInt(o2.getFateValue() - o1.getFateValue()));

        //排除今日佳人
        if(queryParam.getPage() == 1) {
            todayBests.remove(0);
        }

        pageResult.setItems(todayBests);
        return pageResult;
    }
}
